package com.music.loader;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.music.application.Constants;
import com.music.entity.BoardInfo;
import com.music.entity.online.OnlineArtistInfo;
import com.music.entity.online.SearchMusic;
import com.music.entity.online.SongPlay;
import com.music.loader.converter.JsonConverterFactory;
import com.music.lrc.LrcInfo;
import com.music.utils.FileUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by dingfeng on 2016/9/21.
 */
public class DataRequest {

    public static final String TAG = DataRequest.class.getSimpleName();
    private static DataRequest instance;
    private Retrofit mRetrofit;
    private ApiService mApiService;

    public static synchronized DataRequest getInstance() {
        if (instance == null) {
            instance = new DataRequest();
        }
        return instance;
    }

    private DataRequest() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL + "/")
                .addConverterFactory(JsonConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(RetrofitUtil.genericClient())
                .build();
        mApiService = mRetrofit.create(ApiService.class);
    }

    //请求数据回调
    public interface Callback<T> {
        void onSuccess(T data);

        void onError(String err);
    }

    public void getBillboard(String method, String type, int size, final Callback<BoardInfo> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, method);
        params.put(Api.PARAM_TYPE, type);
        params.put(Api.PARAM_SIZE, size);

        mApiService.getBillboard(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                Gson gson = new Gson();
                BoardInfo boardInfo = new BoardInfo();
                try {
                    boardInfo = gson.fromJson(response.body().toString(), BoardInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callback.onSuccess(boardInfo);
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }


    public void getBoardMusicList(String method, String type, int size, int offset, final Callback<BoardInfo> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, method);
        params.put(Api.PARAM_TYPE, type);
        params.put(Api.PARAM_SIZE, size);
        params.put(Api.PARAM_OFFSET, offset);

        mApiService.getBoardMusicList(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                Gson gson = new Gson();
                BoardInfo boardInfo = new BoardInfo();
                try {
                    boardInfo = gson.fromJson(response.body().toString(), BoardInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callback.onSuccess(boardInfo);
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

    public void getOnlineUri(String method, long songId, final Callback<SongPlay> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, method);
        params.put(Api.PARAM_SONG_ID, songId);

        mApiService.getOnlineUri(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                JSONObject object = response.body();
                Log.d("dingfeng", "getOnlineUri:" + object.toString());
                Gson gson = new Gson();
                SongPlay songPlay = new SongPlay();
                try {
                    songPlay = gson.fromJson(response.body().toString(), SongPlay.class);
                    callback.onSuccess(songPlay);
                } catch (Exception e) {
                    e.printStackTrace();
                    callback.onError("返回错误");
                }

            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

    public void getArtistInfo(String method, long tingUid, final Callback<OnlineArtistInfo> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, method);
        params.put(Api.PARAM_TING_UID, tingUid);

        mApiService.getArtistInfo(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                JSONObject object = response.body();
                Gson gson = new Gson();
                OnlineArtistInfo artistInfo = new OnlineArtistInfo();
                try {
                    artistInfo = gson.fromJson(response.body().toString(), OnlineArtistInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callback.onSuccess(artistInfo);
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

    public void getSearchResult(String keyword, final Callback<List<SearchMusic.SearchSong>> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, Api.METHOD_SEARCH_MUSIC);
        params.put(Api.PARAM_QUERY, keyword);

        mApiService.getSearchResult(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                Gson gson = new Gson();
                SearchMusic searchMusic = new SearchMusic();
                try {
                    searchMusic = gson.fromJson(response.body().toString(), SearchMusic.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callback.onSuccess(searchMusic.getSong());
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

    public void getSearchResult(String title, String artist, final Callback<List<SearchMusic.SearchSong>> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, Api.METHOD_SEARCH_MUSIC);
        params.put(Api.PARAM_QUERY, title);
        mApiService.getSearchResult(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                JSONObject object = response.body();
                if (object.has("error_message")) {
                    callback.onError("error");
                    return;
                }
                Gson gson = new Gson();
                SearchMusic searchMusic = new SearchMusic();
                try {
                    searchMusic = gson.fromJson(response.body().toString(), SearchMusic.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callback.onSuccess(searchMusic.getSong());
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

    public void getLrc(final String title, long songId, final Callback<String> callback) {
        Map<String, Object> params = new HashMap<>();
        params.put(Api.PARAM_METHOD, Api.METHOD_LRC);
        params.put(Api.PARAM_SONG_ID, songId);
        mApiService.getLrc(params).enqueue(new retrofit2.Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                JSONObject object = response.body();
                Gson gson = new Gson();
                LrcInfo lrcInfo = new LrcInfo();
                try {
                    lrcInfo = gson.fromJson(response.body().toString(), LrcInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String lrcPath = Constants.LYRICPATH + title + Constants.SUFFIX_LRC;
                if (!TextUtils.isEmpty(lrcInfo.getLrcContent())) {
                    FileUtil.saveLrcFile(lrcPath, lrcInfo.getLrcContent());
                    callback.onSuccess(lrcPath);
                } else {
                    callback.onError("error");
                }
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                callback.onError(t.toString());
            }
        });
    }

}
